
import Utils from '../utils';
import BaseClient from './baseClient';
import http from './HTTP';
import GameConfig from './gameconfig';
import GameData from './gamedata';
import wxAdUtils from './wxAdUtils';

class Wxapi extends BaseClient{

    constructor(config) {
        super();

        Utils.asset(config.gameId,'gameId 不能为空!');

        this.shareTitle = config.shareTitle || '';
        this.wegame = (cc.sys.platform === cc.sys.WECHAT_GAME);  //当前是否为'微信小游戏'运行环境
        this.drawTimers = [];//渲染定时器
        this.LaunchOption = null; //游戏启动参数
        this.wxInfo = {}; // 玩家信息
        this.sharequery = ''; // ??
        this.GameId = config.gameId; // 游戏ID

        wxAdUtils.init(config.bannerAdId,config.intersisterAdId,config.videoAdId,config.gridAdId);

        this.shareTimepoint = 0; //----分享的时间 new Date().getTime()

        this._shareCallback = null;

        //-----------------------------
        this._updateVersion();

        // for test
        this.wxAdUtils = wxAdUtils;
    }

    //初始化微信相关接口
    /**
     * @override
     */
    init() {   // eslint-disable-line

        if (!this.wegame) {
            throw new Error('当前不是微信平台.....');
        }

        let self = this;

        if (!this.LaunchOption) {

            this.LaunchOption = wx.getLaunchOptionsSync();

            console.log('小游戏启动参数 == ', this.LaunchOption);

            //显示‘转发’按钮
            wx.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline'],
                success: function (res) {  // eslint-disable-line
                    // 绑定分享参数
                    if(wx.onShareTimeline){
                        wx.onShareTimeline(() => {
                            return {
                                title: self.shareTitle,
                            };
                        });
                    }
                }
            });

            //'转发'按钮分享信息
            this._appMenuShare(function (res) {
                    if (res.shareTickets.length > 0) {
                        wx.getShareInfo({
                            shareTicket: res.shareTickets[0],
                            success: function (res) {  // eslint-disable-line
                            }
                        });
                    }
                }
            );

            // 游戏回到前台
            wx.onShow(function (res) {
                self.LaunchOption = res;

                if (self.shareTimepoint > 0) {
                    let deta = Date.now() - self.shareTimepoint;
                    self.shareTimepoint = 0;

                    let cktime = GameConfig.getServerCfg().shareTime;

                    // 超过 cktime 秒,表示分享成功
                    if (deta >= cktime * 1000) {
                        // 分享成功
                        self._onShareBack(true);
                    } else {
                        self._onShareBack(false);
                    }
                }
            });

            // 游戏进入到后台
            wx.onHide(function () {
                if (window.GameCom) {
                    window.GameCom.SaveGameDoc && window.GameCom.SaveGameDoc();
                }

                if (window.GamesManager.tryid) {
                    window.GamesManager.timeTry = Date.now();
                }
            });

            //  监听内存警告
            if (wx.onMemoryWarning) {
                wx.onMemoryWarning(function () {
                    wx.triggerGC();
                });
            }
        }
    }

    login(cb) {

        // 微信登陆成功.
        let self = this;
        let wxLoginSuccess = function (res) {
            if (self.LaunchOption && self.LaunchOption.query) {
                res.channel = self.LaunchOption.query.channel || 'none';
            }
            http.GetWithHeader('code', res, function (ret) {
                if (ret.errcode == 0) {
                    cb(ret);
                    self.sharequery = `shareuserid=${GameData.getUserId()}&name=${self.wxInfo.nickName || '*'}`;
                    console.log('sharequery:', self.sharequery);
                } else {
                    cb(ret);
                    console.log('获取服务端数据失败......');
                }
            });
        };

        wx.login({
            success: function success(loginResult) {
                wxLoginSuccess({
                    code: loginResult.code,
                });
            },
            fail: function fail(loginError) {  // eslint-disable-line
                console.log('微信登录wx.login失败');
                cb({errcode: -104});
            }
        });
    }

    /**
     * 检查服务端数据
     */
    checkServerData(){
        // maxscore === 1 表示需要修改数据
        //
        //
        this.login((ret)=>{
            if (ret.errcode == 0) {
                if(!ret.data){
                    throw new Error('Wxapi.Login 登陆返回的数据错误!');
                }

                let gameData = ShSdk.GameData;

                // 检查ID
                if (gameData.localData.userid !== ret.data.userid) {
                    gameData.localData.userid = ret.data.userid;
                    gameData.saveData(3);
                }

                // 宠物泡泡专用
                if(ret.data && ret.data.maxscore === 1){
                    if(ret.data.serverjson){
                        let serverJsonObj = JSON.parse(ret.data.serverjson);
                        gameData.localData.userjson = JSON.stringify(serverJsonObj.newData);
                        gameData._dumpLocalData();
                        gameData.saveData(2);
                        gameData.UploadSyncFlag();
                        console.log('数据更新完毕!');
                        wx.showModal({
                            title:'提示',
                            showCancel:false,
                            content:'数据需要更新,请退出游戏!',
                            confirmText:'确定',
                            complete:function () {
                                // 1s后退出游戏
                                setTimeout(function () {
                                    wx.exitMiniProgram({
                                        complete:function () {}
                                    });
                                },1000);
                            }
                        });
                    }
                }
            }
        });
    }

    onLoginError() {
        // 进行简单的 api 兼容检查
        if (window.wx && window.wx.showModal) {
            wx.showModal({
                title: '提示',
                content: '获取玩家信息失败',
                showCancel: false,
                confirmText: '确定',
            });
        }
    }

    //保存到微信
    saveToPlatform(data) {
        let upnames = ['userid', 'score'];  //需要上传微信的字段
        let updata = {};
        for (let k in upnames) {
            updata[upnames[k]] = data[upnames[k]];
        }
        let kvlist = [];
        for (let k in updata) {
            let d = {};
            d.key = '' + k;
            d.value = '' + updata[k];
            kvlist.push(d);
        }


        wx.setUserCloudStorage({
            KVDataList: kvlist,
            success: function (res) {  // eslint-disable-line
            },
            fail: function (res) {   // eslint-disable-line
                cc.sys.localStorage.setItem('datasync', 'xxx');
            },
            complete: function (res) {
                console.log('上传微信 complete==', res);
            },
        });
    }

    setUserInfo(userInfo){
        this.wxInfo = userInfo;
    }


    /**
     * @param opValue
     * @param obj
     */
    playVideoOrShare(opValue,obj){
        if(opValue === ShSdk.OP_PLAY_VIDEO){
            // 视频缓存失败是否切换分享
            let auto = 1;
            if(obj.key){
                if(obj.hasOwnProperty('auto')){
                    auto = obj.auto;
                }
            }else{
                auto = 0;
            }
            this._showVideoAd({
                auto:auto,
                key:obj.key,
                success:obj.success
            });
        }else if(opValue === ShSdk.OP_SHARE){
            this._share(obj);
        }else{
            console.warn(`-------opValue:${opValue} 可能错误!`);
        }
    }

    /**
     * obj:{
     *     key: shareKey, {string}
     *     success:function(){}
     * }
     * @param obj
     */
    _share(obj){

        Utils.asset(obj.key,'key 不能为空!');

        this._increaseOpId();

        this._shareCallback = obj.success;
        let sharePoint = ShSdk.config.SharePoint[obj.key];
        let dotPoint = ShSdk.config.SharePoint[obj.key];

        // 打点
        this._shareRequest(this.GameId,dotPoint,2);

        // 获取分享需要的资源
        let url = 'https://wxgameapi.sihai-inc.com/appsharematter/index?mattercid=' + sharePoint;
        http.Request(url,(ret)=>{
            if (ret && ret.code == 200) {
                let titles = ret.data.share_title;
                let imgurl = ret.data.share_image;
                this._realShare(titles, imgurl, dotPoint);
            }
        });
    }

    /**
     * obj:{
     *     key: shareKey, // 视频缓存失败切换分享时,使用的分享key,
     *     success:function(){} // 成功回调
     *     auto: boolean  // 视频缓存失败 是否切换分享
     * }
     * @param obj
     */
    _showVideoAd(obj){

        if(obj.auto){
            Utils.asset(obj.key,'key 不能为空!');
        }

        this._increaseOpId();

        // 判断是否缓存成功
        if(wxAdUtils.VideoAdUtils.videoCachedSuccess()){
            wxAdUtils.VideoAdUtils.showVideoAd(obj.success);
        }else{
            // 还没有缓存成功,再缓存一次
            wxAdUtils.VideoAdUtils.cacheVideoAd();

            if(obj.auto){
                // 分享
                this._share(obj);
            }else{
                window.ShSdk.getVideoFailTip('获取广告失败,请稍后重试!');
            }
        }
    }


    //-------------------------------------
    // @override ads
    cacheVideo(){
        wxAdUtils.VideoAdUtils.cacheVideoAd();
    }
    showBannerAd(){
        wxAdUtils.BannerAdUtils.showBannerAd();
    }
    hideBannerAd(){
        wxAdUtils.BannerAdUtils.hideBanner();
    }
    showInterAd(){
        wxAdUtils.InterstitialAdUtils.showInterstialAd();
    }
    showGridAd(obj){
        wxAdUtils.GridAdUtils.showGridAd(obj);
    }
    hideGridAd(){
        wxAdUtils.GridAdUtils.hideGridAd();
    }

    // 跳转
    moreAd(url) {
        http.Request(url, ret => {
            if (ret && ret.code == 200) {
                if (wx.navigateToMiniProgram) {
                    wx.navigateToMiniProgram({
                        appId: ret.data.first_appid,//直接跳转的目标
                        path: ret.data.first_path,
                        success: function () {
                        },
                        fail: function () {
                        },
                        complete: function () {
                        }
                    });
                } else {
                    this.showAd(ret.data.big_image);
                }
            }
        });
    }

    // 查看广告
    showAd(adurl) {
        wx.previewImage({
            urls: [adurl],
            success: res => {  // eslint-disable-line
            }
        });
    }

    // 显示 微信授权按钮
    showButton() {
        let self = this;
        wx.getSystemInfo({
            success: function (ret) {
                let AuthButton = wx.createUserInfoButton({
                    type: 'text',
                    text: '',
                    style: {
                        left: 0,
                        top: 0,
                        width: ret.screenWidth,
                        height: ret.screenHeight,
                        backgroundColor: 'rgba(255, 255, 255, 0)',
                    }
                });

                AuthButton.onTap(function (res) {
                    AuthButton.destroy();
                    if (res.userInfo) {
                        GameData.saveUserInfo(res.userInfo);
                    }
                });

                AuthButton.show();
            }
        });
    }

    _getShareParam(code, pngid) {   // eslint-disable-line
        let fsquery = this.sharequery;
        return fsquery;
    }

    _updateVersion() {
        const updateManager = wx.getUpdateManager();
        updateManager.onCheckForUpdate(function (res) {  // eslint-disable-line
            // console.log(res.hasUpdate)
        });
        updateManager.onUpdateReady(function () {
            updateManager.applyUpdate();
        });
        updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
        });
    }

    // 应该是分享打点
    _shareRequest(gameid, shareid, sharetype) {
        let url = `https://wxgameapi.sihai-inc.com/appshare/push?game_id=${gameid}&share_id=${shareid}&share_type=${sharetype}`;
        http.Request(url, ret => {  // eslint-disable-line
        });
    }

    _onShareBack(bSuccess){
        if(this._shareCallback){
            if(bSuccess){
                // 分享成功
                this._shareCallback(ShSdk.OP_SHARE);
            }else{
                window.ShSdk.shareFailTip(GameConfig.getServerCfg().sharetext1);
            }
        }
    }

    // 分享
    _realShare(title, imgurl, dotPoint) {   // eslint-disable-line
        this.shareTimepoint = (dotPoint > 0) ? Date.now() : 0;
        wx.shareAppMessage({
            title: title,
            imageUrl: imgurl,
            query: this._getShareParam(dotPoint, 200),
        });
    }

    //菜单‘转发’按钮分享事件
    _appMenuShare(cb) {
        let url = 'https://wxgameapi.sihai-inc.com/appsharematter/index?mattercid=' + ShSdk.config.SharePoint.zhaunfa;
        let self = this;
        http.Request(url, function (ret) {
            if (ret && ret.code == 200) {
                let titles = ret.data.share_title;
                let imgurl = ret.data.share_image;
                wx.onShareAppMessage(function (res) {  // eslint-disable-line
                    let ShareOption = {
                        title: titles,
                        imageUrl: imgurl,
                        query: self._getShareParam(ShSdk.config.SharePoint.zhaunfa, 200),   //转发，默认图
                        success: cb
                    };
                    return ShareOption;
                });
            }
        });
    }

    //================================================
    // 排行榜
    //渲染开放域shareCanvas
    RenderCanvas(uiNode, param) {
        if (param.shareTicket) {
            this.LaunchOption.shareTicket = param.shareTicket;
        }

        let openDataContext = wx.getOpenDataContext();
        let sharedCanvas = openDataContext.canvas;
        sharedCanvas.width = param.width;
        sharedCanvas.height = param.height;
        param.userid = GameData.getUserId();

        if (this.LaunchOption.shareTicket) {
            param.shareTicket = this.LaunchOption.shareTicket;
        } else {
            if (param.cmd === 'grouprank') {
                uiNode.getComponent(cc.Sprite).spriteFrame = null;
                return;
            }
        }

        if (param.view === 'me') {
            param.cmd = 'friendrank';
        }
        //数据过期时间
        param.reftime = '2018-04-09';
        console.log('发送:', param);
        openDataContext.postMessage(param);
        let texture = new cc.Texture2D();
        let spriteFrame = new cc.SpriteFrame(texture);
        let sprite = uiNode.getComponent(cc.Sprite);
        let draw = function () {
            texture.initWithElement(sharedCanvas);
            texture.handleLoadedTexture();
            sprite.spriteFrame = spriteFrame;
            //sprite.spriteFrame._refreshTexture(texture);
        };

        let timeId = setInterval(draw, 1000 * 0.2);
        this.drawTimers.push(timeId);
    }

    //渲染开放域shareCanvas
    BeyondInit(uiNode, param) {
        let openDataContext = wx.getOpenDataContext();
        let sharedCanvas = openDataContext.canvas;
        sharedCanvas.width = param.width;
        sharedCanvas.height = param.height;
        param.userid = GameData.getUserId();
        param.cmd = 'beyondinit';
        openDataContext.postMessage(param);
        let texture = new cc.Texture2D();
        let spriteFrame = new cc.SpriteFrame(texture);
        let sprite = uiNode.getComponent(cc.Sprite);

        let draw = function () {
            texture.initWithElement(sharedCanvas);
            texture.handleLoadedTexture();
            sprite.spriteFrame = spriteFrame;
        };
        let timeId = setInterval(draw, 1000 * 0.2);
        this.drawTimers.push(timeId);
    }

    BeyondUpdate(score) {
        let openDataContext = wx.getOpenDataContext();
        openDataContext.postMessage({cmd: 'beyondcheck', score: score});
    }

    //分页 //{cmd:'page',index:1}
    RenderPage(param) {
        let openDataContext = wx.getOpenDataContext();
        openDataContext.postMessage(param);
    }

    //渲染结算。//取消排行榜绘画调度定时器，在排行榜页面关闭时调用
    RenderEnd() {
        wx.getOpenDataContext().postMessage({cmd: 'clear'});
        this.drawTimers.forEach(timeId => {
            clearInterval(timeId);
        });
        this.drawTimers = [];
    }
}

export default Wxapi;

/**
 OnBannerErr(banOK){
        let banNode = cc.find('connect/bannerAD', this.node);
        if(banOK){
            banNode.active = false;
        }else{
            banNode.active = true;
            banNode.getComponent('dynamicImage').showDynamicImage(119, 119005);
        }
    },
 */




